<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-form-item prop="title" :label="$t('news.title')">
        <el-input v-model="dataForm.title" :placeholder="$t('news.title')"></el-input>
      </el-form-item>
      <el-form-item prop="subtitle" label="描述">
        <el-input v-model="dataForm.subtitle" placeholder="请输入描述"></el-input>
      </el-form-item>
      <el-form-item prop="type" label="内容类型">
        <ren-radio-group v-model="dataForm.type" dict-type="program_list_type" placeholder="内容类型"></ren-radio-group>
      </el-form-item>
      <el-form-item prop="top" label="是否置顶">
        <el-radio-group v-model="dataForm.top">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="tagIds" label="标签">
        <el-checkbox-group v-model="dataForm.tagIds">
          <el-checkbox :label="item.id" :value="item.id" v-for="(item, index) in tagList" :key="index"> {{ item.label }} </el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="图片" prop="uploadUrl">
        <el-upload v-model:file-list="imgList" :action="uploadUrl" list-type="picture-card" :on-remove="handleRemove" :before-upload="uploadBeforeUploadHandle" :on-success="uploadSuccessHandle">
          <el-icon><Plus /></el-icon>
        </el-upload>

        <!-- <el-upload :action="uploadUrl" :multiple="false" :before-upload="uploadBeforeUploadHandle" :on-success="uploadSuccessHandle">
          <el-button size="small" type="primary">点击上传</el-button>
          <template v-slot:tip> 支持扩展名：.png .jpg </template>
        </el-upload> -->
      </el-form-item>
      <el-form-item prop="content" :label="$t('news.content')">
        <TinyMce v-model="dataForm.content"></TinyMce>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import WangEditor from "@/components/wang-editor/index.vue";
import { getToken } from "@/utils/cache";
import app from "@/constants/app";
import TinyMce from "@/components/tinymce/src/index.vue";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const uploadUrl = ref(`${app.api}/sys/oss/upload?token=${getToken()}&subPrefix=mp`);

const dataForm = reactive({
  id: "",
  title: "",
  content: "",
  subtitle: "",
  top: 0,
  imgList: [],
  tagIds: [],
  type: ""
});

const rules = ref({
  title: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  content: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  tagIds: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  optType: [{ required: true, message: t("validate.required"), trigger: "blur" }]
});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    getInfo(id);
  }
  getTagList();
};

let tagList = ref([]);
const getTagList = () => {
  baseService.get(`/wechat/program_tag/list`).then((res) => {
    tagList.value = res.data;
  });
};

let imgList = ref([]);
const getInfo = (id: number) => {
  baseService.get(`/wechat/program_content/${id}`).then((res) => {
    console.log("res: ", res);
    if (!res.data.tagIds) {
      res.data.tagIds = [];
    }
    if (!res.data.imgList) {
      res.data.imgList = [];
    }
    res.data.optType = '1'
    imgList.value = res.data.imgList.map((item, index) => {
      return {
        name: index,
        url: item
      };
    });
    Object.assign(dataForm, res.data);
  });
};

const handleRemove = (uploadFile, uploadFiles) => {
  dataForm.imgList = uploadFiles.map((item) => item.url);
};

const uploadBeforeUploadHandle = (file: any) => {
  if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/gif") {
    ElMessage.error(t("upload.tip", { format: "jpg、png、gif" }));
    return false;
  }
};
const uploadSuccessHandle = (res: any) => {
  if (res.code !== 0) {
    return ElMessage.error(res.msg);
  }
  // dataForm.coverImage = res.data.src;
  dataForm.imgList.push(res.data.src);
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }

    (!dataForm.id ? baseService.post : baseService.put)("/wechat/program_content", dataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};
defineExpose({
  init
});
</script>
